package com.jindi.jacococli.biz.config;


import com.alibaba.nacos.api.naming.pojo.ListView;
import com.jindi.jacococli.biz.business.model.ServiceProject;
import com.jindi.jacococli.biz.business.service.GitLabService;
import com.jindi.jacococli.biz.business.service.NacosFetchService;
import com.jindi.jacococli.biz.constant.Constant;
import com.jindi.jacococli.biz.utils.JSONUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.gitlab4j.api.models.Project;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class ServiceProjectConfig implements InitializingBean {

    private static final Logger LOGGER = LoggerFactory.getLogger(ServiceProjectConfig.class);

    @Resource
    private NacosFetchService nacosFetchService;

    @Resource
    private GitLabService gitLabService;

    @Value("${service.list}")
    private String serviceList;

    private List<ServiceProject> projects;

    public List<ServiceProject> getProjects() {
        return projects;
    }

    public void updateProjects(String value) {
        if (StringUtils.isBlank(value)) {
            LOGGER.info("service.list update is blank");
        }
        try {
            List<ServiceProject> serviceProjects = JSONUtils.parseServiceProject(value);
            ListView<String> nacosServices = nacosFetchService.serviceAll();
            if (Objects.isNull(nacosServices) || CollectionUtils.isEmpty(nacosServices.getData())) {
                LOGGER.info("nacos获取服务错误");
                return;
            }
            Map<String, String> serviceMap = nacosServices.getData().stream()
                    .collect(Collectors.toMap(Function.identity(), Function.identity(), (a, b) -> b));
            List<ServiceProject> newProjectConfig = serviceProjects.stream().filter(sp -> project(sp, serviceMap)).collect(Collectors.toList());
            projects = newProjectConfig;
        } catch (Exception e) {
            LOGGER.error("service.list update analyze error", e);
        }
    }


    private boolean project(ServiceProject serviceProject,  Map<String, String> serviceMap) {
        String serviceName = serviceProject.getServiceName();
        if (StringUtils.isBlank(serviceName)) {
            LOGGER.info("serviceName is blank");
            return false;
        }
        String projectName = serviceProject.getProjectName();
        if (StringUtils.isBlank(projectName) || !projectName.contains(Constant.BACKSLASH)
                || projectName.split(Constant.BACKSLASH).length != Constant.INT2) {
            LOGGER.info("projectName is blank, 必须包括项目组的内容");
            return false;
        }
        List<Project> existProject = gitLabService.projectFindByServiceName(projectName);
        String mapServiceName = serviceMap.get(serviceName);
        if (StringUtils.isBlank(mapServiceName) || CollectionUtils.isEmpty(existProject)) {
            return false;
        }
        return true;
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        updateProjects(serviceList);
    }
}
